import { Router } from 'express';
import bcrypt from 'bcryptjs';
import { db } from '../utils/db.js';

const router = Router();

router.get('/login', (req, res) => {
  res.render('login', { error: null, title: '登录' });
});

router.post('/login', (req, res) => {
  const { username, password } = req.body;
  const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
  if (!user || !bcrypt.compareSync(password, user.password_hash)) {
    return res.status(401).render('login', { error: '用户名或密码错误', title: '登录' });
  }
  req.session.user = {
    id: user.id,
    username: user.username,
    role: user.role,
    company_name: user.company_name || ''
  };
  res.redirect('/dashboard');
});

router.get('/logout', (req, res) => {
  req.session.destroy(() => {
    res.redirect('/auth/login');
  });
});

router.get('/register', (req, res) => {
  res.render('register', { error: null, title: '注册' });
});

router.post('/register', (req, res) => {
  const { username, password, role, company_name, legal_person, phone } = req.body;
  if (!['BIDDER', 'TENDERER'].includes(role)) {
    return res.status(400).render('register', { error: '非法的角色类型', title: '注册' });
  }
  const exists = db.prepare('SELECT 1 FROM users WHERE username = ?').get(username);
  if (exists) {
    return res.status(400).render('register', { error: '用户名已存在', title: '注册' });
  }
  const hash = bcrypt.hashSync(password, 10);
  db.prepare('INSERT INTO users (username, password_hash, role, company_name, legal_person, phone) VALUES (?,?,?,?,?,?)')
    .run(username, hash, role, company_name || null, legal_person || null, phone || null);
  res.redirect('/auth/login');
});

export default router;


